package com.wsm.executor.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @name: ExecutorPoolConfig
 * @Author: wangshimin
 * @Date: 2020/8/3 0003  下午 18:34
 * @Description:
 */
@Configuration
@ConditionalOnProperty(prefix = "executor", value = {"open"}, havingValue = "true")
public class ExecutorPoolConfig {

    @Value("${executor.corePoolSize:0}")
    private int corePoolSize;

    @Value("${executor.maxPoolSize:0}")
    private int maxPoolSize;

    @Value("${executor.keepAliveTime:100}")
    private long keepAliveTime;

    /**
     * 创建默认线程池
     */
    @Bean("commonPool")
    public ThreadPoolExecutor commonPool() {
        if (corePoolSize == 0) {
            corePoolSize = Runtime.getRuntime().availableProcessors();
        }
        if (maxPoolSize == 0) {
            maxPoolSize = Integer.MAX_VALUE;
        }
        return new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

}
